#include <stdio.h>
#include <sys/types.h>          /* See NOTES */
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <sys/time.h>
#include <arpa/inet.h>
#include <stdlib.h>
#include <errno.h>


int main(int argc, char const *argv[]){
    //创建socket
    int sockfd;
     const char *message = "hello world";


    //创建一个socket文件描述符
    sockfd = socket(AF_INET, SOCK_DGRAM, 0);
    if(sockfd < 0)
    {
        perror("sock err");
        return -1;
    }

    //指定连接的服务器的地址
    struct sockaddr_in addr;
    addr.sin_family = AF_INET;
    addr.sin_port = htons(8888);  //端口号
    addr.sin_addr.s_addr = inet_addr("127.0.0.1");  //IP



    int addrlen = sizeof(addr);
    // if(connect(sockfd, (struct sockaddr *)&addr, addrlen) < 0)
    // {
    //     perror("connect err");
    //     return -1;
    // }

    // printf("connect success\n");

    struct timeval tv;
    tv.tv_sec =3;
    tv.tv_usec =0;
    setsockopt(sockfd,SOL_SOCKET,SO_RCVTIMEO,&tv,sizeof(tv));

    
    char buf[64]="请求数据";
    int ret = -1;
    if(sendto(sockfd,buf,64,0,(struct sockaddr*)&addr,addrlen) == -1){
        perror("send err");
        return -1;
    }
    while (ret < 0){
        printf("等待数据\n");
        ret = recvfrom(sockfd,buf,64,0,(struct sockaddr*)&addr,&addrlen) ;  
        if(ret < 0){
            if(errno == EAGAIN){
                printf("超时\n");
                if(sendto(sockfd,buf,64,0,(struct sockaddr*)&addr,addrlen) == -1){
                    perror("send err");
                    return -1;
                }
            }else{
                close(sockfd);
                
                return -1;
            }
            
        }
    }

    if(ret < 0)
    {
        perror("send err");
        return -1;
    }

 

    close(sockfd);

    return 0;
}
